package tech.xs.common.file.client;

import cn.hutool.core.util.IdUtil;
import tech.xs.api.domain.enums.FileScenario;
import tech.xs.common.file.client.domain.exception.FileClientException;
import tech.xs.common.framework.domain.constant.Symbol;

import java.io.InputStream;

public abstract class AbstractFileClient implements FileClient {

    protected String getUseFileNameFilePath(FileScenario scenario, String fileName) {
        return scenario.getPath() + fileName;
    }

    protected String getFilePath(FileScenario scenario, String fileName) {
        if (scenario.isFile()) {
            return scenario.getPath();
        }
        int pointIndex = fileName.lastIndexOf(Symbol.POINT);
        String path = scenario.getPath();
        if (!path.endsWith(Symbol.SLASH_STR)) {
            path += Symbol.SLASH_STR;
        }
        if (pointIndex == -1) {
            return path + IdUtil.simpleUUID();
        }
        String extension = fileName.substring(pointIndex + 1).toLowerCase();
        if (!scenario.getExtension().contains(extension)) {
            throw new FileClientException("文件类型不支持");
        }
        return path + IdUtil.simpleUUID() + extension;
    }

    @Override
    public String upload(FileScenario scenario, String fileName, InputStream stream) {
        return upload(scenario, fileName, stream, false);
    }

    @Override
    public String upload(FileScenario scenario, String fileName, InputStream stream, boolean isUseFileName) {
        String path = null;
        if (isUseFileName) {
            path = getUseFileNameFilePath(scenario, fileName);
        } else {
            path = getFilePath(scenario, fileName);
        }
        return upload(path, stream);
    }

}
